var jianyueProfile = {};
var jianyueSetting = {};
var jianyueChannel = {};
var baseUrl = "";
var unReadNum = 0;
var poping = null;
//CLOSE OPEN MIN
var windowStatus = "CLOSE";

var TEXT = {
	TIP : "提示",
	CONFIRM : "确定",
	CANCEL : "取消",
	RECEIVE : "新消息："
};
var GUIDE_POLICY = {
	SHOW : "0",
	POP : "1",
	HIDE : "3"
};

function jianyueParse(responseText) {
    var res;    
    if (typeof(JSON) == 'undefined'){   
         res = eval("("+responseText+")");    
    }else{  
         res = JSON.parse(responseText); 
    } 
    return res;
}

function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) {
		return unescape(r[2]);
	}
	return null;
}
function jianyueBoot() {
	var scripts = document.scripts;
	var scriptsLen = scripts.length;
	var jianyueUrl = "";
	for (var i = 0; i < scriptsLen; i++) {
		if (scripts[i].src.indexOf("visitor-access") > 0) {
			jianyueUrl = scripts[i].src;
			break;
		}
	}
	var params = {};
	var idx = jianyueUrl.indexOf("?");
	var src = jianyueUrl.slice(0, idx);
	params.src = src;
	var paramsInUrl = jianyueUrl.slice(idx + 1).split("&");
	for (var i = 0, l = paramsInUrl.length; l > i; i++) {
		var tmp = paramsInUrl[i].split("=");
		params[tmp[0]] = tmp.length > 1 ? tmp[1] : "";
	}
	var a = src.indexOf("http://") >= 0 ? src.substring(7) : src.substring(8);
	var b = a.indexOf("/");
	params.domain = params.src.substring(0, src.indexOf("http://") >= 0 ? 7 + b : 8 + b);
	//引用简约客服的网站
	params.quoter = window.location.origin;
	if (!params.quoter) {
		params.quoter = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
	}
	jianyueProfile = params;
	if (typeof window.addEventListener != "undefined") {
		window.addEventListener("message", jianyueMessageHandler, false);
	} else {
		if (typeof window.attachEvent != "undefined") {
			window.attachEvent("onmessage", jianyueMessageHandler);
		}
	}
}
function jianyueMessageHandler(e) {
	if (jianyueProfile.domain.indexOf((e.origin).split("://")[1]) < 0) {
		return;
	}
	if(e.data) {
		var jsond = jianyueParse(e.data);
		if(jsond.event == "close") {
			if(window.jQuery) {
				$("#jianyue-iframe").attr("src", "");
			} else {
				document.getElementById("jianyue-iframe").src = "";
			}
			showFixedDialog(false);
			showFixedBtn(true);
			showBadge(false);
			windowStatus = "CLOSE";
		} else if(jsond.event == "min") {
			showFixedDialog(false);
			showFixedBtn(true);
			showBadge(false);
			windowStatus = "MIN";
		} else if(jsond.event == "message") {
			if(windowStatus == "MIN") {
				if(jianyueProfile.pid == jsond.pid) {
					unReadNum = unReadNum + 1; 
				}
				if(unReadNum > 0) {
					showBadge(true, jsond.text.substring(0, 10) + "...");
				}
			}
		} else if(jsond.event == "callback") {
		}
	}
}

/**
 */
var JIANYUE_TERMINAL_TYPE = {PC:0, MOBILE:1};
/**
 */
function jianyueGetCurrentDevice() {
	if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
		return JIANYUE_TERMINAL_TYPE.MOBILE;
	} else {
		return JIANYUE_TERMINAL_TYPE.PC;
	}
}
function jianyueMobileClient() {
	return jianyueGetCurrentDevice() == JIANYUE_TERMINAL_TYPE.MOBILE;
}
function jianyueCreatePannel() {
	var bodys = document.getElementsByTagName("body");
	var jianyue_containerElement = null;
	if (bodys.length <= 0 || jianyueMobileClient() == true) {
		jianyue_containerElement = document.documentElement;
	} else {
		jianyue_containerElement = bodys[0];
	}
	var pcCssStr = "#jianyue-fixed-dialog{z-index:999999; position:fixed; display:none;overflow:hidden;background-color: white;bottom:0px;right:0px;width:400px;height:480px;border-radius: 10px;}";
	pcCssStr = pcCssStr + "#jianyue-iframe{clear:both;position:absolute;top:0;right:0;bottom:0;left:0;width:100%;height:100%;border:0;padding:0;margin:0;float:none;}";
	pcCssStr = pcCssStr + "#jianyue-fixed-btn{z-index: 999999;position:fixed; display:none;width: auto;height: auto;cursor: pointer;right:0px;bottom:0px;}";
	pcCssStr = pcCssStr + "#jianyue-btn-text-div{text-align: center;font-size:16px;width:100%}";
	pcCssStr = pcCssStr + "#jianyue-btn-badge-p{display:none;right: 0;background-color: #FF2254;border-radius: 4px;position: absolute;font-size: 10px;font-style: normal;text-align: center;min-width: 20px;padding: 3px;}";
	pcCssStr = pcCssStr + "#btnImg{max-width: 100px;max-height: 100px;border-radius: 15px;}";
	pcCssStr = pcCssStr + "#jianyue_tip_div{z-index:999999; position:fixed;top:100;right:0;bottom: 100px;cursor:pointer;color: #00A4F5;background-color: #A54397;border-radius: 4px;opacity: 0.5;}";
	    
	
	var mobileCssStr = '';
	mobileCssStr = mobileCssStr + '#jianyue-fixed-dialog{z-index: 999999;position:fixed;top:0;right:0;bottom:0;left:0;width:100%;height:100%;display:none;overflow:hidden;background-color:white;width:100%;height:100%}';
	mobileCssStr = mobileCssStr + '#jianyue-iframe{position:fixed;top:0;right:0;bottom:0;left:0;width:100%;height:100%;border:0;padding:0;margin:0;float:none;background:0}';
	mobileCssStr = mobileCssStr + "#jianyue-fixed-btn{z-index: 999999;position:fixed; display:none;width: auto;height: auto;cursor: pointer;right:0px;bottom:0px;}";
	mobileCssStr = mobileCssStr + "#jianyue-btn-text-div{text-align: center;font-size:16px;width:100%}";
	mobileCssStr = mobileCssStr + "#jianyue-btn-badge-p{display:none;right: 0;background-color: #FF2254;border-radius: 4px;position: absolute;font-size: 10px;font-style: normal;text-align: center;min-width: 20px;padding: 3px;}";
	mobileCssStr = mobileCssStr + "#btnImg{max-width: 100px;max-height: 100px;border-radius: 15px;}";
	if (document.createStyleSheet) { //
		var $style = document.createStyleSheet();
		if (jianyueMobileClient() == true) {
            $style.cssText = mobileCssStr; //要添加的css
        } else {
            $style.cssText = pcCssStr; //要添加的css
        }
	} else {
		var $style = document.createElement("style");
		$style.innerHTML = pcCssStr;
		if (jianyueMobileClient() == true) {
            $style.innerHTML = mobileCssStr; //要添加的css
        } else {
            $style.innerHTML = pcCssStr; //要添加的css
        }
		jianyue_containerElement.appendChild($style);
	}
	var jianyue_tip_div = document.createElement("div");
	jianyue_tip_div.setAttribute("id", "jianyue_tip_div");
	jianyue_tip_div.onclick = jianyueKefu;
	jianyue_containerElement.appendChild(jianyue_tip_div);
	
	//引导按钮的DIV
	var jiaxnyue_fixed_btn_div = document.createElement("div");
	jiaxnyue_fixed_btn_div.setAttribute("id", "jianyue-fixed-btn");
	jiaxnyue_fixed_btn_div.onclick = jianyueKefu;
	//按钮的未读消息数提示
	var badge = document.createElement("p");
	badge.setAttribute("id", "jianyue-btn-badge-p");
	jiaxnyue_fixed_btn_div.appendChild(badge);
	//按钮的图片
	var $btnImageDiv = document.createElement("div");
	$btnImageDiv.align = "center";
	$btnImageDiv.innerHTML = "<img id='btnImg' src=''/>";
	jiaxnyue_fixed_btn_div.appendChild($btnImageDiv);
	//按钮的文字
	var $btnTextDiv = document.createElement("div");
	$btnTextDiv.setAttribute("id", "jianyue-btn-text-div");
	$btnTextDiv.innerHTML = "<span id='btnSpan'></span>";
	jiaxnyue_fixed_btn_div.appendChild($btnTextDiv);
	//形成按钮
	jianyue_containerElement.appendChild(jiaxnyue_fixed_btn_div);
	
	//增加聊天iframe
	var jianyue_fixed_dialog_div = document.createElement('div');
    jianyue_fixed_dialog_div.setAttribute("id", "jianyue-fixed-dialog");

    var $dialogDiv = document.createElement("div");
    jianyue_fixed_dialog_div.appendChild($dialogDiv);

    var jianyue_dialog_iframe = document.createElement("iframe");
    jianyue_dialog_iframe.setAttribute("id", "jianyue-iframe");
    jianyue_dialog_iframe.setAttribute("frameborder", "0");
    $dialogDiv.appendChild(jianyue_dialog_iframe);

    jianyue_containerElement.appendChild(jianyue_fixed_dialog_div);
}
function jianyueKefu() {
	//未读提示消息清零
	unReadNum = 0;
	if(poping) {//停止可能延迟弹出的邀请窗口
		clearTimeout(poping);
	}
	//记录窗口状态为打开的
	windowStatus = "OPEN";
	
	var url = jianyueProfile.domain + "/visitor/VisitorDpAct.do?method=logon&pid=" + jianyueProfile.pid + "&channel=" + jianyueProfile.channel + "&windowShowType=" + jianyueSetting.windowShowType + "&windowOpenType=" + jianyueSetting.windowOpenType;
	if(jianyueProfile.quoter){
		url = url + "&quoter=" + encodeURIComponent(jianyueProfile.quoter);
	}
	if(jianyueProfile.ty == "TY"){
		url = url + "&ty=TY";
	}
	try {
		if (typeof(eval(jianyueInitData)) == "function") {
			var jsond = jianyueInitData();
			if(jsond.tid) {
				url = url + "&tid=" + jsond.tid;
			}
			if(jsond.timestamp) {
				url = url + "&timestamp=" + jsond.timestamp;
			}
			if(jsond.ttoken) {
				url = url + "&ttoken=" + jsond.ttoken;
			}
			if(jsond.tcrm) {
				url = url + "&tcrm=" + encodeURIComponent(encodeURIComponent(JSON.stringify(jsond.tcrm)));
			}
	    }
	} catch(e) {
	}
    
	
	if(jianyueSetting.windowOpenType == "P") {//弹出窗口的模式
		var w = jianyueSetting.windowWidth;
		var h = jianyueSetting.windowHeight;
		if(jianyueSetting.windowWidth <=0 || jianyueSetting.windowHeight <=0) {
			w = 880;
			h = 600;    
		}
		var iTop = (window.screen.availHeight  - h) / 2; 
		var iLeft = (window.screen.availWidth  - w) / 2;
		window.open(url, "newwindow", "height=" + h + ", width=" + (w + 10) + ", toolbar=no, menubar=no,top="+ iTop + ",left=" + iLeft +",scrollbars=no, resizable=no, Resizable=no, location=no, status=no");
	} else {//嵌入页面显示的模式
		var iframe = document.getElementById("jianyue-iframe");
		if(!iframe.src || iframe.src == "" || iframe.src.indexOf("visitor") < 0) {
			iframe.src = url;
		} 
		showFixedDialog(true);
		showFixedBtn(false);
	}
}
function jianyueAjax(opt, forceXDomainRequest) {
	var xmlHttp = null;
	var xmlHttpType = null;
	var seed = new Date().getTime();
	opt = opt || {};
	opt.method = opt.method.toUpperCase();
	if (opt.method == "GET") {
		opt.url = opt.url + "&seed=" + seed || "";
	} else {
		opt.url = opt.url || "";
	}
	opt.async = opt.async || true;
	opt.success = opt.success || function () {
	};
	opt.error = opt.error || function () {
	};
	opt.data = opt.data || null;
	if (window.XMLHttpRequest && !forceXDomainRequest) {
		xmlHttp = new XMLHttpRequest();
		xmlHttpType = "XMLHttpRequest";
	} else {
		if (window.XDomainRequest) {
			xmlHttp = new XDomainRequest();
			xmlHttpType = "XDomainRequest";
		}
	}
	if (xmlHttpType == "XDomainRequest") {
		xmlHttp.onload = function () {
			opt.success(xmlHttp.responseText);
		};
		xmlHttp.onerror = function () {
			opt.error();
		};
		
		xmlHttp.open(opt.method, opt.url);
		xmlHttp.withCredentials = true;
		xmlHttp.crossDomain= true;	
		if (!opt.data) {
			xmlHttp.send();
		} else {
			xmlHttp.setRequestHeader("CONTENT-TYPE", "application/x-www-form-urlencoded;charset=UTF-8");
			xmlHttp.send();
		}
	} else {
		if (xmlHttpType = "XMLHttpRequest") {
			try {	
				xmlHttp.open(opt.method, opt.url, opt.async);
				xmlHttp.withCredentials = true;
				xmlHttp.crossDomain= true;		
				if (!opt.data) {
					xmlHttp.send();
				} else {
					xmlHttp.setRequestHeader("CONTENT-TYPE", "application/x-www-form-urlencoded;charset=UTF-8");
					xmlHttp.send(opt.data);
				}
				xmlHttp.onreadystatechange = function () {
					if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
						opt.success(xmlHttp.responseText);
					}
				};
			}
			catch (e) {
				jianyueAjax(opt, true);
			}
		} else {
			opt.error();
		}
	}
}


function showBadge(show, text) {
	if(show) {
		document.getElementById("jianyue-btn-badge-p").style.display = "block";
		document.getElementById("jianyue_tip_div").style.display = "block";
	} else {
		document.getElementById("jianyue-btn-badge-p").style.display = "none";
		document.getElementById("jianyue_tip_div").style.display = "none";
		unReadNum = 0;
	}
	document.getElementById("jianyue-btn-badge-p").innerHTML = unReadNum;
	//简单显示文字
	document.getElementById("jianyue_tip_div").innerHTML = TEXT.RECEIVE + text;	
}

function showFixedDialog(show) {
	if(show == true) {
		if(window.jQuery) {
			$("#jianyue-fixed-dialog").show(500);
		} else {
			document.getElementById("jianyue-fixed-dialog").style.display = "block";
		}
	} else {
		if(window.jQuery) {
			$("#jianyue-fixed-dialog").hide(500);
		} else {
			document.getElementById("jianyue-fixed-dialog").style.display = "none";
		}
	}
}
//显示或者隐藏
function showFixedBtn(show) {
	//如果设置的是隐藏按钮，那就不用显示了，直接隐藏
	if (jianyueSetting.guidePolicy == GUIDE_POLICY.HIDE) {
		document.getElementById("jianyue-fixed-btn").style.display = "none";
		return;
	}
	if(show == true) {
		if(window.jQuery) {
			$("#jianyue-fixed-btn").show(500);
		} else {
			document.getElementById("jianyue-fixed-btn").style.display = "block";
		}
	} else {
		if(window.jQuery) {
			$("#jianyue-fixed-btn").hide(500);
		} else {
			document.getElementById("jianyue-fixed-btn").style.display = "none";
		}
	}
}


(function() {
	jianyueBoot();
	jianyueCreatePannel();
	var pageTitle = document.title;
	if(pageTitle.length > 200) {
		pageTitle = pageTitle.substring(0, 200);
	}
	pageTitle = encodeURIComponent(encodeURIComponent(pageTitle));
	var pageUrl = encodeURIComponent(encodeURIComponent(window.location.href)); 
	//读取配置之后处理
	//../file/load.do?method=get&amp;bizType=SETTING&amp;fileName=visitor.png
	var url = jianyueProfile.domain + "/visitor/VisitorDpAct.do?method=getConfig&pid=" + jianyueProfile.pid + "&channel=" + jianyueProfile.channel + "&pageTitle=" + pageTitle + "&pageUrl=" + pageUrl;
	SETTING_FILE_PATH = jianyueProfile.domain + "/file/load.do?method=get&bizType=SETTING&fileName=";
	jianyueAjax({method:"GET", url:url, async:true, success:function (resp) {
		var obj = jianyueParse(resp);
		jianyueSetting = obj.setting;
		jianyueChannel = obj.channel;
		if(jianyueMobileClient() == true) {//手机端都采用小窗口模式显示
			jianyueSetting.windowShowType = "S";
		}
		jianyueSession = obj.session;
		crm = obj.crm;
		
		//重置窗口的宽高
		if(jianyueMobileClient() == false) {
			if(jianyueSetting.windowWidth <=0) {
				document.getElementById("jianyue-fixed-dialog").style.width = "100%";
			} else {
				document.getElementById("jianyue-fixed-dialog").style.width = jianyueSetting.windowWidth + "px";
			}
			if(jianyueSetting.windowHeight <=0) {
				document.getElementById("jianyue-fixed-dialog").style.height = "100%";
			} else {
				document.getElementById("jianyue-fixed-dialog").style.height = jianyueSetting.windowHeight + "px";
			}
		}
		
		//普通按钮引导
		if (jianyueSetting.guidePolicy == GUIDE_POLICY.SHOW || jianyueSetting.guidePolicy == GUIDE_POLICY.POP) {
			document.getElementById("btnImg").src = SETTING_FILE_PATH + jianyueSetting.orgHeader;
			if(jianyueSetting.guideButtonText != ""){
				document.getElementById("btnSpan").innerHTML = jianyueSetting.guideButtonText;
			} else {
				document.getElementById("btnSpan").style.display = "none";
			}
			showFixedBtn(true);
		} else {//隐藏按钮
			
		}
		//有正在聊天的会话
		if(jianyueSession) {
			//DIV打开的模式，如果存在会话则需要自动显示
			if(jianyueSetting.windowOpenType == "D") {
				jianyueKefu();
			}
		} else {
			if (jianyueSetting.guidePolicy == GUIDE_POLICY.POP && (!crm || crm.status==0)) {
				var time = jianyueSetting.guidePopLater && jianyueSetting.guidePopLater > 0 ? jianyueSetting.guidePopLater * 1000 : 3000;
				poping = setTimeout(function () {
					layer.confirm(jianyueSetting.guidePopTip, {title:TEXT.TIP, shadeClose:true, btn:[TEXT.CONFIRM, TEXT.CANCEL]}, function () {
						jianyueKefu();
						layer.closeAll();
					});
				}, time);
			}		
		}
	}, error:function (response) {
		alert("简约客服的参数有误");
	}});
})();